package com.cmbchina.service;

import com.cmbchina.entity.Currency;
import com.cmbchina.entity.ExchangeRate;
import com.cmbchina.entity.SohuExchangeRate;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * 汇率服务
 *  从搜狐服务模块获取汇率并进行适配转换，为兼容已存模块搜狐获取汇率服务接口，通过类适配器实现防腐
 */
public class SohuExchangeRateService extends SohuService implements ExchangeRateService {

    @Override
    public ExchangeRate getRate(Currency from, Currency to) {
        //1、从搜狐网站获取新浪格式汇率，getSohuExchangeRate为已存模块接口
        SohuExchangeRate sohuRate = getSohuExchangeRate(from, to);
        //2、将搜狐汇率格式转换为当前系统的汇率格式
        ExchangeRate rate = convertExhangeRate(sohuRate);
        return rate;
    }

    /**
     * 搜狐汇率格式转
     * @param sohuRate
     * @return
     */
    private ExchangeRate convertExhangeRate(SohuExchangeRate sohuRate){
        if(Objects.isNull(sohuRate)){
            throw new IllegalArgumentException("汇率不能为null");
        }

        //数据转换
        Currency sourceCurrency = sohuRate.getFromCurrency();
        Currency targetCurrency = sohuRate.getToCurrency();
        BigDecimal rate = sohuRate.getRate();
        return new ExchangeRate(rate, sourceCurrency, targetCurrency);
    }

}
